package com.mainbo.modular.system.controller;

import cn.stylefeng.roses.core.base.controller.BaseController;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.mainbo.core.shiro.SessionKey;
import com.mainbo.core.shiro.ShiroKit;
import com.mainbo.core.util.Result;
import com.mainbo.modular.jms.MessageTypes;
import com.mainbo.modular.system.dao.PtClassMapper;
import com.mainbo.modular.system.model.PtClass;
import com.mainbo.modular.system.model.PtOrg;
import com.mainbo.modular.system.model.PtSchoolClassroom;
import com.mainbo.modular.system.service.IPtOrgService;
import com.mainbo.modular.system.service.IPtSchoolClassroomService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jms.annotation.EnableJms;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.beans.factory.annotation.Autowired;
import com.mainbo.core.log.LogObjectHolder;
import org.springframework.web.bind.annotation.RequestParam;
import com.mainbo.modular.system.model.PtSchoolBuilding;
import com.mainbo.modular.system.service.IPtSchoolBuildingService;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 场所管理控制器
 *
 * @author moshang
 * @Date 2020-03-09 09:25:29
 */
@Controller
@RequestMapping("/ptSchoolBuilding")
public class PtSchoolBuildingController extends BaseController {
    private static final Logger logger= LoggerFactory.getLogger(PtSchoolBuildingController.class);

    private String PREFIX = "/system/ptSchoolBuilding/";

    @Autowired
    private IPtSchoolBuildingService ptSchoolBuildingService;
    @Resource
    private IPtOrgService orgService;
    @Resource
    private IPtSchoolClassroomService schoolClassroomService;
    @Resource
    private PtClassMapper classMapper;

    /**
     * 跳转到场所管理首页
     */
    @RequestMapping("")
    public String index(Model model) {
        PtOrg org = ShiroKit.getSessionAttr(SessionKey.CURRENT_ORG);
        if ((org == null)) {
            model.addAttribute("orgId","0");
            return PREFIX + "ptSchoolBuilding_org.html";
        }
        model.addAttribute("orgId",org.getId());
        return PREFIX + "ptSchoolBuilding_list.html";
    }

    /**
     * 跳转到添加场所管理
     */
    @RequestMapping("/ptSchoolBuilding_add")
    public String ptSchoolBuildingAdd(String orgId,Model model) {
        PtOrg org = orgService.selectById(orgId);
        model.addAttribute("org",org);
        return PREFIX + "ptSchoolBuilding_add.html";
    }

    /**
     * 跳转到修改场所管理
     */
    @RequestMapping("/ptSchoolBuilding_update/{ptSchoolBuildingId}")
    public String ptSchoolBuildingUpdate(@PathVariable String ptSchoolBuildingId, Model model) {
        PtSchoolBuilding ptSchoolBuilding = ptSchoolBuildingService.selectById(ptSchoolBuildingId);
        model.addAttribute("item",ptSchoolBuilding);
        LogObjectHolder.me().set(ptSchoolBuilding);
        return PREFIX + "ptSchoolBuilding_edit.html";
    }

    /**
     * 跳转到修改场所管理
     */
    @RequestMapping("/openShowInfo/{ptSchoolBuildingId}")
    public String openShowInfo(@PathVariable String ptSchoolBuildingId, Model model) {
        PtSchoolBuilding ptSchoolBuilding = ptSchoolBuildingService.selectById(ptSchoolBuildingId);
        model.addAttribute("item",ptSchoolBuilding);
        LogObjectHolder.me().set(ptSchoolBuilding);
        return PREFIX + "ptSchoolBuilding_info.html";
    }
    /**
     * 获取场所管理列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(PtSchoolBuilding schoolBuilding) {
        EntityWrapper<PtSchoolBuilding> wrapper=new EntityWrapper<>();
        wrapper.eq("org_id",schoolBuilding.getOrgId());
        if (StringUtils.isNotEmpty(schoolBuilding.getName())) {
           wrapper.like("name",schoolBuilding.getName());
        }

        wrapper.orderBy(" create_time",false);
        wrapper.eq("deleted",0);
        List<PtSchoolBuilding> schoolBuildings = ptSchoolBuildingService.selectList(wrapper);
        return schoolBuildings;
    }

    /**
     * 新增场所管理
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Result add(PtSchoolBuilding ptSchoolBuilding) {
        Result result = new Result();
        try {
            ptSchoolBuilding.setCreateTime(new Date());
              ptSchoolBuildingService.insert(ptSchoolBuilding);
            if(null!=ptSchoolBuilding.getId()){
                ptSchoolBuildingService.sendMessage(MessageTypes.SCHOOLBUILDING_ADD,ptSchoolBuilding);
            }
            result.setMsg("操作成功");
            result.setCode(Result.SUCCESS);
        } catch (Exception e) {
            result.setCode(Result.FAIL);
            result.setMsg("操作失败");
            logger.error("操作失败",e);
        }
        return result;
    }

    /**
     * 删除教学楼
     * @param id
     * @param deleted
     * @return
     */
    @RequestMapping("/delete/{id}")
    @ResponseBody
    public Result delSchbuild(@PathVariable String id,Boolean deleted){
        Result result = new Result();
        result.setCode(Result.SUCCESS);
        try {
            if(StringUtils.isNotBlank(id)){
                ptSchoolBuildingService.updateDeleteFlag(id);
            }
            result.setMsg("操作成功");
            logger.info("组织机构管理删除-删除教学楼，教学楼id"+id);
        } catch (Exception e) {
            result.setMsg("操作失败");
            result.setCode(Result.FAIL);
        }
        return result;
    }
    /**
     * 修改场所管理
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Result update(PtSchoolBuilding ptSchoolBuilding) {
        Result result = new Result();
        ptSchoolBuilding.setModifyTime(new Date());
        try {
            PtSchoolBuilding  oldSchoolBuilding=ptSchoolBuildingService.selectById(ptSchoolBuilding.getId());
            boolean update = ptSchoolBuildingService.updateById(ptSchoolBuilding);
            if (update){
                if (!oldSchoolBuilding.getName().equals(ptSchoolBuilding.getName())){
                    //更新教室中教学楼名称及位置
                   EntityWrapper<PtSchoolClassroom> param=new EntityWrapper<>();
                    param.eq("building_id",ptSchoolBuilding.getId());
                    param.eq("deleted",0);
                    param.eq("enable",1);
                    List<PtSchoolClassroom> classRooms=schoolClassroomService.selectList(param);
                    if (classRooms.size()>0) {
                        for (PtSchoolClassroom classRoom : classRooms) {
                            classRoom.setBuildingName(ptSchoolBuilding.getName());
                            String position = classRoom.getBuildingName() + classRoom.getFloor() + "层" + classRoom.getSerialNo() + "号";
                            classRoom.setClassroomPosition(position);
                            classRoom.setModifyTime(new Date());
                            classRoom.setLastupId(ShiroKit.getUser().getId());
                            schoolClassroomService.updateById(classRoom);
                            if (classRoom.getIsUsed() == 1) {
                               PtClass param1 = new PtClass();
                                param1.setClassroomId(classRoom.getId());
                                PtClass classInfo = classMapper.selectOne(param1);
                                if (classInfo != null) {
                                    classInfo.setClassroomName(classRoom.getBuildingName() + classRoom.getName());
                                    classMapper.updateById(classInfo);
                                }
                            }
                        }
                    }
                }
                PtSchoolBuilding building = ptSchoolBuildingService.selectById(ptSchoolBuilding.getId());
                ptSchoolBuildingService.sendMessage(MessageTypes.SCHOOLBUILDING_UPDATE,building);
            }
            result.setMsg("操作成功");
            result.setCode(Result.SUCCESS);
        } catch (Exception e) {
            result.setCode(Result.FAIL);
            result.setMsg("操作失败");
        }
        return result;
    }

    /**
     * 禁用教学楼
     * @param id
     * @param m
     * @return
     */
    @RequestMapping("/disableSchbuild/{id}")
    public String disabledSchbuild(@PathVariable String id, Model m) {
        if(StringUtils.isNotBlank(id)){
            PtSchoolBuilding building = ptSchoolBuildingService.selectById(id);
            m.addAttribute("building",building);
        }
        return PREFIX+"disabledSchbuild.html";
    }


    /**
     * 更新教学楼禁用状态
     * @param schbuild
     * @return
     */
    @RequestMapping("/updateEnable")
    @ResponseBody
    public Result updateEnable(PtSchoolBuilding schbuild){
        Result result = new Result();

        try {
             ptSchoolBuildingService.updateEnable(schbuild);
             if (schbuild.getEnable()){
                 result.setMsg("启用成功");
             }else {
                 result.setMsg("禁用成功");
             }
         result.setCode(Result.SUCCESS);
        } catch (Exception e) {
            result.setCode(Result.FAIL);
            result.setMsg("操作失败");
        }
        return result;
    }
}
